// 同时发送异步请求的次数
import http from './http.js'

let ajaxTimes = 0;
export const request = (options) => {
	ajaxTimes++;

	const baseUrl = http.host;
	return new Promise(function (resolve, reject) {
		uni.showLoading({
			title: '加载中',
			mask: true
		})
		
		// 请求参数
		const requestParams = {
			url: baseUrl + options.url,
			method: options.method || 'GET',
			data: options.data || {},
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
				'cookie': uni.getStorageSync('cookie'),
				'third':'true'
			},
			timeout: 30000,
			// 忽略SSL证书验证问题
			verify: false,
			sslVerify: false,
			success(result){
				if(result==null||result==undefined||result=='undefined'){
					uni.showToast({
						title:"后端请求失败"+result
					}) 
					uni.reLaunch({
						url: "/pages/login/login"
					})
					return;
				}
				
				if(result.data.code=='NO-LOGIN'){
					uni.showToast({
						title:"登录失效重新登录"
					})
					uni.reLaunch({
						url: "/pages/login/login"
					})
					return;
				}
				
				if (uni.getStorageSync('cookie')) {
					resolve(result);
				} else {
					if(options.url.includes("thirdLogin")){
						resolve(result);
					}else{
						uni.showToast({
							title:"登录失效重新登录"
						})
						uni.reLaunch({
							url: "/pages/login/login"
						})
					}
				}
			},
			fail(err) {
				console.error('网络请求失败:', err)
				
				// 如果HTTPS失败且有HTTP备用地址，尝试HTTP
				if (baseUrl.includes('https') && http.httpHost && err.errMsg && err.errMsg.includes('Network Error')) {
					console.warn('尝试HTTP备用地址...')
					// 使用HTTP地址重试
					uni.request({
						...requestParams,
						url: http.httpHost + options.url,
						verify: true,
						sslVerify: true
					})
					return
				}
				
				// 处理具体的错误类型
				let errorMessage = '网络连接失败'
				if (err.errMsg) {
					if (err.errMsg.includes('Network Error')) {
						errorMessage = '网络连接不可用，请检查网络设置'
					} else if (err.errMsg.includes('timeout')) {
						errorMessage = '请求超时，请稍后重试'
					} else if (err.errMsg.includes('CERT')) {
						errorMessage = '证书验证失败，请联系管理员'
					}
				}
				
				if (uni.getStorageSync('cookie')) {
					uni.showToast({
						title: errorMessage,
						icon: 'none',
						duration: 3000
					})
					reject(err)
				} else {
					if(options.url.includes("thirdLogin")){
						uni.showToast({
							title: errorMessage,
							icon: 'none',
							duration: 3000
						})
						reject(err)
					}else{
						uni.showToast({
							title:"登录失效重新登录"
						})
						uni.reLaunch({
							url: "/pages/login/login"
						})
						reject(err)
					}
				}
			},
			complete(){
				ajaxTimes--;
				if (ajaxTimes === 0) {
					uni.hideLoading({
						fail:() =>{},
						success:()=>{},
						complete: (complete) => {}
					});
				}
			}
		};
		
		uni.request(requestParams);
	});
};